package algotithm.leetcode.listnode.test92;

import algotithm.leetcode.listnode.ListNode;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/17-20:19
 * @URL https://leetcode-cn.com/problems/reverse-linked-list-ii/
 * @Title 92. 反转链表 II
 */
public class Solution {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);

        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = null;

        int m = 2, n = 4;

        Solution solution = new Solution();
        ListNode listNode = solution.reverseBetween(head, m, n);
        while (listNode != null) {
            System.out.print(listNode.val + " ");
            listNode = listNode.next;
        }
    }

    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;
        while (m > 1) {
            pre = pre.next;
            m--;
            n--;
        }
        head = pre.next;
        while (n > 1) {
            ListNode next = head.next;
            head.next = head.next.next;
            next.next = pre.next;
            pre.next = next;
            n--;
        }
        return dummy.next;
    }

}
